package com.example.demo;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with Software Dept.
 * <p> {@code Ehcache}
 *
 * @author : tianbaolei
 * @date : 2020-06-18 14:54
 * Description:
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Ehcache {

    @Test
    public void test() {
        String path1 = System.getProperty("java.io.tmpdir");
        System.out.println("path1 = " + path1);
        String path2 = System.getProperty("user.dir");
        System.out.println("path2 = " + path2);
    }

    @Test
    public void cacheTest01() {

        // 创建缓存管理器
        String path = this.getClass().getResource("/").getPath();
        System.out.println("================>" + path);
        // classpath:ehcache.xml
        CacheManager cacheManager = CacheManager.create("E:/IdeaProjects/baolei-mine/weiyi-demo-mp/target/classes/ehcache.xml");

        // 获取缓存对象
        Cache cache = cacheManager.getCache("HelloWorldCache");

        // 创建元素
        Element element = new Element("key1", "value");

        // 将元素添加到缓存
        cache.put(element);

        Element value = cache.get("key1");
        System.out.println(value);
        System.out.println(value.getObjectValue());

        /// cache.remove("key1");

        Map<String, Object> p1 = new HashMap<String, Object>() {{
            put("mapKey1", "mapValue1");
            put("mapKey2", "mapValue2");
        }};
        Element pelement = new Element("xm", p1);
        cache.put(pelement);
        Element pelement2 = cache.get("xm");
        System.out.println(pelement2.getObjectValue());

        System.out.println(cache.getSize());

        // 7. 刷新缓存
        cache.flush();

        // 8. 关闭缓存管理器
        cacheManager.shutdown();

    }
}
